<?php

namespace App\Models;

use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RewardApply extends Model
{
    protected  $table='reward_time_apply';

    protected $fillable = [
        'apply_user_id	',
        'reward_time',
        'project_id',
        'content',
        'verify_status',
        'verify_msg',
        'attachment'
    ];

    protected $casts = [
        'attachment' => 'array',
    ];

    public function project() {
        return $this->belongsTo('App\Models\Project', 'project_id', 'id');
    }

    public function team() {
        return $this->belongsTo('App\Models\Team', 'team_id', 'id');
    }

    public function org() {
        return $this->belongsTo('App\Models\Org', 'org_id', 'id');
    }

    public function user() {
        return $this->belongsTo('App\User', 'apply_user_id', 'id');
    }

    public function volunteer() {
        return $this->belongsTo('App\Models\Volunteer', 'apply_user_id', 'user_id');
    }

    public function syncRewardTime() {
        if (!$this->id) {
            return false;
        }

        $userProject = UserProject::where('user_id', $this->apply_user_id)->where('project_id', $this->project_id)->first();

        $orgInfo = Org::find($this->org_id);
        $scoreConf = $orgInfo->getScoreConf();
        $addScore = $this->reward_time * $scoreConf['reward_time'];
        $this->volunteer->increment('score', $addScore);

        DB::table('user_score_item')->insert(['user_id'=>$this->apply_user_id, 'type'=>0, 'score'=>$addScore, 'remark'=>'参加志愿活动']);
        Log::info('SCORE 申请补录时长奖励积分 userId:'.$this->apply_user_id.'  score:'.$addScore);

        return $userProject->plusTime($this->reward_time)
            && $this->team->plusTime($this->reward_time)
            &&  $this->volunteer->plusTime($this->reward_time);
    }
}
